package com.alibaba.citrus.ots.b2b.trade.order.repository.impl;

import com.alibaba.citrus.ots.b2b.trade.order.repository.OrderQueryRepository;
import com.alibaba.citrus.ots.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.ots.common.constant.SaleOrderConstants;
import com.alibaba.citrus.ots.common.exception.FunctionException;
import com.alibaba.citrus.ots.common.exception.RepositoryException;
import com.alibaba.citrus.ots.common.util.DateUtils;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.QueryWarehouseByIdRequest;
import com.epoch.app.bcots.model.dto.WarehouseInfo;
import com.epoch.app.bcots.platform_enhance.SaleOrderTag;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.bcots.service.UnifiedInventoryService;
import com.epoch.app.otsb2btradecenter.domain.order.dto.LoadOrderListRequest;
import com.epoch.app.otsb2btradecenter.domain.order.dto.LoadOrderRequest;
import com.epoch.app.otsb2btradecenter.domain.order.model.Order;
import com.epoch.app.otsb2btradecenter.domain.order.service.OrderService;
import com.epoch.app.otsb2btradecenter.domain.orderline.dto.LoadListResponse;
import com.epoch.app.otsb2btradecenter.domain.orderline.dto.OrderLineLoadListRequest;
import com.epoch.app.otsb2btradecenter.domain.orderline.model.OrderLine;
import com.epoch.app.otsb2btradecenter.domain.orderline.service.OrderLineService;
import com.epoch.app.otsb2btradecenter.dto.OrderDetailDTO;
import com.epoch.app.otsb2btradecenter.dto.request.OrderPageQueryRequest;
import com.epoch.app.otsb2btradecenter.dto.request.OrderQueryRequest;
import com.epoch.app.otsb2btradecenter.dto.response.OrderPageQueryResponse;
import com.epoch.app.otsb2btradecenter.dto.response.OrderQueryResponse;
import com.epoch.app.otsb2btradecenter.enums.OrderStatus;
import com.epoch.app.otsb2btradecenter.model.dto.PageQueryOrderEsListRequest;
import com.epoch.app.otsb2btradecenter.model.dto.SelectCombox;
import com.epoch.app.otsb2btradecenter.obtcsaleorderindex.model.ObtcSaleOrderIndex;
import com.epoch.app.otsb2btradecenter.obtcsaleorderindex.service.ObtcSaleOrderIndexService;
import com.epoch.app.otsb2btradecenter.sdo.DeliverOrderSDO;
import com.epoch.app.otsb2btradecenter.sdo.DeliveryOrderDetailSDO;
import com.epoch.app.otsb2btradecenter.sdo.OrderSDO;
import com.epoch.app.otsforecastsales.model.dto.ActivitySDO;
import com.epoch.app.otsforecastsales.model.dto.PageQueryForecastRequest;
import com.epoch.app.otsforecastsales.otsforecastorderquery.service.OtsForecastOrderQueryService;
import com.epoch.app.otsforecastsales.sdo.ForecastOrderSDO;
import com.epoch.app.otsplatformenhance.dictionaryquery.service.DictionaryQueryService;
import com.epoch.app.otsplatformenhance.model.dto.PageQueryAddressListRequest;
import com.epoch.app.otsplatformenhance.model.dto.PageQueryAddressListResponse;
import com.epoch.app.otsplatformenhance.model.dto.QueryDictionaryRequest;
import com.epoch.app.otsplatformenhance.sdo.CustomerAddressSDO;
import com.epoch.app.otsplatformenhance.sdo.DictionarySDO;
import com.epoch.app.otsplatformenhance.service.OtsPlatformEnhanceService;
import com.epoch.app.otspricecenter.api.creditquery.service.CreditQueryService;
import com.epoch.app.otsunifiedinventory.api.forecastwarehouse.dto.QueryWarehouseByFactoryCodeAndWarehouseCodeRequest;
import com.epoch.app.otsunifiedinventory.api.forecastwarehouse.service.ForecastWarehouseService;
import com.epoch.app.otsunifiedinventory.model.dto.WarehouseInfoDTO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Component
public class OrderQueryRepositoryImpl implements OrderQueryRepository {
    private Log log = Log.getLogger(OrderQueryRepositoryImpl.class);

    private static final String ORDER_TIME_START = " 00:00:00";
    private static final String ORDER_TIME_END = " 23:59:59";

    private static final String UPDATE_TIME_START = " 00:00:00";
    private static final String UPDATE_TIME_END = " 23:59:59";

    @Resource
    private CreditQueryService creditQueryService;
    //单据原因
    private static final String ORDER_REASON_TYPE = "orderReason";

    //交货单，feature key
    private static final String DELIVERY_NO = "deliveryOrderLineNo";

    //调拨单业务ID
    private static final String ALLOCATE_ORDER_BIZ_ID = "allocateOrderBizId";

    //调拨单业务ID
    private static final String ALLOCATE_ORDER_ID = "allocateOrderId";

    //运输方式
    private static final String SHIP_METHOD_TYPE = "shipMethod";

    private static final String STAN_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    @Resource
    private OrderService orderService;

    @Resource
    private ObtcSaleOrderIndexService obtcSaleOrderIndexService;

    @Resource
    private DictionaryQueryService dictionaryQueryService;

    @Resource
    private OtsPlatformEnhanceService otsPlatformEnhanceService;

    @Resource
    private UnifiedInventoryService unifiedInventoryService;

    @Resource
    private ForecastWarehouseService forecastWarehouseService;
    @Resource
    private OrderLineService orderLineService;

    @Resource
    private OtsForecastOrderQueryService orderQueryService;
    @Autowired(required = false)
    private BaseDataService baseDataService;


    @Override
    @RepositoryInvoker
    public PageResult<List<OrderPageQueryResponse>> pageQuery(OrderPageQueryRequest request) {
        LoadOrderListRequest loadOrderListRequest = queryRequestConverter(request);
        Result<List<Order>> listResult = orderService.loadOrderList(loadOrderListRequest);
        if (CollectionUtils.isEmpty(listResult.getResult())) {
            return new PageResult<>(new ArrayList<>(), 0);
        }
        List<Order> orderList = listResult.getResult();
        List<OrderPageQueryResponse> orderPageQueryResponses = orderList.stream().map(order -> {
            OrderPageQueryResponse orderPageQueryResponse = new OrderPageQueryResponse();
            if (null != order.getId()) {
                orderPageQueryResponse.setId(String.valueOf(order.getId()));
            }
            if (!StringUtils.isEmpty(order.getOrderType())) {
                String desc = Arrays.stream(SaleOrderTag.values()).filter(x -> order.getOrderType().equals(x.getCode()))
                        .map(SaleOrderTag::getDesc).findFirst().orElse(null);
                orderPageQueryResponse.setOrderType(desc);
            }
            if (StringUtils.isNotBlank(order.getFeatures())) {
                Map<String, String> features = JSONObject.parseObject(order.getFeatures(), Map.class);
                orderPageQueryResponse.setMessageDesc(features.get(SaleOrderConstants.EXT_MESSAGE));
            }
            orderPageQueryResponse.setOuterId(order.getOuterOrderId());
            orderPageQueryResponse.setOrderTag(order.getOrderTag());
            orderPageQueryResponse.setOrderBizId(order.getOrderBizId());
            orderPageQueryResponse.setCustomerName(order.getCustomerName());
            orderPageQueryResponse.setSalesOrganization(order.getOrganizationName());
            orderPageQueryResponse.setBuzChannel(order.getChannelName());
            orderPageQueryResponse.setGoodsGroup(order.getProductGroupName());
            orderPageQueryResponse.setSaleChannel(order.getSaleChannelName());
            orderPageQueryResponse.setSaleDepartment(order.getDepartmentName());
            orderPageQueryResponse.setCreator(order.getCreatorName());
            orderPageQueryResponse.setRemark(order.getRemark());
            orderPageQueryResponse.setReceiveAddressCode(order.getReceiveAddressCode());
            orderPageQueryResponse.setReceiveDetailAddressName(order.getReceiveDetailAddress());
            orderPageQueryResponse.setWareHouseCode(order.getWareHouseCode());
            orderPageQueryResponse.setFrontOrderId(order.getFrontOrderId());
            if (order.getStatus() != null) {
                orderPageQueryResponse.setStatusCode(String.valueOf(order.getStatus()));
                String desc = Arrays.stream(OrderStatus.values()).filter(s -> order.getStatus().equals(s.getCode()))
                        .map(OrderStatus::getDesc).findFirst().orElse(null);
                orderPageQueryResponse.setStatus(desc);
            }
            if (null != order.getGmtCreate()) {
                SimpleDateFormat spf = new SimpleDateFormat(STAN_DATETIME_PATTERN);
                String format = spf.format(order.getGmtCreate());
                orderPageQueryResponse.setOrderTime(format);
            }

            //add by 皓晖 at 20211216 for 新增加版本号 begin
            orderPageQueryResponse.setSyncVersion(order.getSyncVersion());
            //add by 皓晖 at 20211216 for 新增加版本号 end

            return orderPageQueryResponse;
        }).collect(Collectors.toList());
        return PageResult.of(orderPageQueryResponses, listResult.getTotal());
    }


    @Override
    @RepositoryInvoker
    public OrderQueryResponse query(OrderQueryRequest request) {
        if (StringUtil.isNotEmpty(request.getId())) {
            LoadOrderRequest loadOrderRequest = LoadOrderRequest.builder().build();
            loadOrderRequest.setId(request.getId());
            Order order = orderService.loadOrder(loadOrderRequest);
            if (Objects.isNull(order)) {
                throw new RepositoryException("OTS-05-001-10-16-004");
            }
            OrderQueryResponse orderQueryResponse = OrderQueryResponseConverter(order);
            //获取预报订单业务单号
            if (StringUtils.isNotBlank(order.getFrontOrderId())) {
                Result<List<ForecastOrderSDO>> forecastOrderList = orderQueryService.queryForecastOrderList(new PageQueryForecastRequest() {{
                    setId(order.getFrontOrderId());
                    setStart(0);
                    setLimit(1000);
                }});
                if (Objects.nonNull(forecastOrderList) && CollectionUtils.isNotEmpty(forecastOrderList.getResult())) {
                    orderQueryResponse.setFrontOrderBizId(forecastOrderList.getResult().get(0).getOrderBizId());
                }
            }

            if (StringUtils.isNotBlank(order.getFeatures())) {
                JSONObject jsonObject = JSONObject.parseObject(order.getFeatures());
                orderQueryResponse.setAllocateOrderId(jsonObject.getString(ALLOCATE_ORDER_ID));
                orderQueryResponse.setAllocateOrderBizId(jsonObject.getString(ALLOCATE_ORDER_BIZ_ID));
            }

            QueryDictionaryRequest queryDictionaryRequest = new QueryDictionaryRequest();
            //获取单据原因的名称
            if (StringUtils.isNotBlank(order.getCreateReason())) {
                queryDictionaryRequest.setDictCode(ORDER_REASON_TYPE);
                Result<DictionarySDO> dictionarySDOResult = dictionaryQueryService.querySingle(queryDictionaryRequest);
                dictionarySDOResult.getResult().getDictValueList().stream().forEach(x -> {
                    if (x.getValueData().equals(order.getCreateReason())) {
                        orderQueryResponse.setOrderReasonName(x.getValueName());
                    }
                });
            }

            //获取配送方式名称
            if (StringUtils.isNotBlank(order.getTransportModeCode())) {
                queryDictionaryRequest.setDictCode(SHIP_METHOD_TYPE);
                Result<DictionarySDO> dictionarySDOResult = dictionaryQueryService.querySingle(queryDictionaryRequest);
                dictionarySDOResult.getResult().getDictValueList().stream().forEach(x -> {
                    if (x.getValueData().equals(order.getTransportModeCode())) {
                        orderQueryResponse.setDeliveryMethodName(x.getValueName());
                    }
                });
            }

            //获取收货地址
            if (null != order.getReceiveAddressCode()) {
                if (StringUtils.isNotBlank(order.getReceiveAddressCode())) {
                    PageQueryAddressListRequest pageQueryAddressListRequest = new PageQueryAddressListRequest();
                    pageQueryAddressListRequest.setAddressCode(order.getReceiveAddressCode());
                    pageQueryAddressListRequest.setCustomerCode(order.getCustomerCode());
                    pageQueryAddressListRequest.setOrgSaleOrganizationCode(order.getOrganizationCode());
                    pageQueryAddressListRequest.setChannelCode(order.getChannelCode());
                    pageQueryAddressListRequest.setItemGroup(order.getProductGroupCode());

                    PageQueryAddressListResponse response = otsPlatformEnhanceService.pageQueryAddressList(pageQueryAddressListRequest);
                    if (!response.getSuccess() || CollectionUtils.isEmpty(response.getResult())) {
                        throw new FunctionException("OTS-05-001-10-16-014", "未查询到客户收货地址数据");
                    }

                    CustomerAddressSDO customerAddressSDO = response.getResult().get(0);
                    if (StringUtils.isBlank(customerAddressSDO.getOrgSaleOrganizationCode())) {
                        throw new FunctionException("OTS-05-001-10-16-015", "未查询到客户组织编码");

                    }

                    orderQueryResponse.setAddressName(customerAddressSDO.getAddressName());
                    orderQueryResponse.setSalesmanName(customerAddressSDO.getPrincipalName());
                }

            }

            //获取发货仓库
            if (StringUtils.isNotBlank(order.getWareHouseName())) {
                orderQueryResponse.setShippingWarehouseName(order.getWareHouseName());
            } else {
                if (null != order.getWareHouseCode()) {
                    QueryWarehouseByIdRequest queryCargoZoneByIdRequest = new QueryWarehouseByIdRequest();
                    queryCargoZoneByIdRequest.setId(order.getWareHouseCode());


                    Result<WarehouseInfo> warehouseInfoResult = unifiedInventoryService.queryWarehouseById(queryCargoZoneByIdRequest);
                    if (warehouseInfoResult != null && warehouseInfoResult.getResult() != null) {
                        orderQueryResponse.setShippingWarehouseName(warehouseInfoResult.getResult().getName());
                    } else {
                        QueryWarehouseByFactoryCodeAndWarehouseCodeRequest queryWarehouseByFactoryCodeAndWarehouseCodeRequest = new QueryWarehouseByFactoryCodeAndWarehouseCodeRequest();
                        queryWarehouseByFactoryCodeAndWarehouseCodeRequest.setWarehouseCode(order.getWareHouseCode());
                        Result<List<WarehouseInfoDTO>> listResult = forecastWarehouseService.queryWarehouseByFactoryCodeAndWarehouseCode(queryWarehouseByFactoryCodeAndWarehouseCodeRequest);

                        if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
                            orderQueryResponse.setShippingWarehouseName(listResult.getResult().get(0).getName());
                        }
                    }
                }
            }


            OrderLineLoadListRequest orderLineLoadListRequest = new OrderLineLoadListRequest();
            orderLineLoadListRequest.setMainOrderId(request.getId());
            orderLineLoadListRequest.setStart(0);
            orderLineLoadListRequest.setLimit(999);
            LoadListResponse loadListResponse = orderLineService.loadList(orderLineLoadListRequest);
            if (loadListResponse.getResult() != null) {
                List<OrderLine> result = loadListResponse.getResult();
                List<OrderDetailDTO> orderDetailDTOList = result.stream().map(orderLine -> {
                    OrderDetailDTO orderDetailDTO = OrderDetailDTOConverter(orderLine);
                    //将库存单位转换为一个销售单位list，用于页面展示

                    if (orderLine.getSaleUnit() != null && orderLine.getSaleUnitName() != null
                            && orderLine.getUnitConvert() != null) {
                        List<SelectCombox> saleUnitList = new ArrayList<>();
                        SelectCombox selectCombox = new SelectCombox();
                        selectCombox.setLabel(orderLine.getSaleUnitName());
                        selectCombox.setValue(orderLine.getSaleUnit());
                        selectCombox.setExt(orderLine.getUnitConvert());
                        saleUnitList.add(selectCombox);
                        orderDetailDTO.setSaleUnitList(saleUnitList);
                    }
                    if (StringUtils.isNotBlank(orderLine.getFeatures())) {
                        HashMap<String, String> hashMap = JSONObject.parseObject(orderLine.getFeatures(), HashMap.class);
                        if (!MapUtils.isEmpty(hashMap) && Objects.nonNull(hashMap.get(DELIVERY_NO))) {
                            orderDetailDTO.setDeliveryNo(null == hashMap.get(DELIVERY_NO) ? "" : String.valueOf(hashMap.get(DELIVERY_NO)));
                        }
                        if (!MapUtils.isEmpty(hashMap)) {
                            //手工价格
                            orderDetailDTO.setManualPrice(StringUtils.isNotBlank(hashMap.get(SaleOrderConstants.MANUAL_PRICE)) ? hashMap.get(SaleOrderConstants.MANUAL_PRICE) : null);
                            //手工总金额
                            orderDetailDTO.setManualTotalAmount(StringUtils.isNotBlank(hashMap.get(SaleOrderConstants.MANUAL_TOTAL_AMOUNT)) ? hashMap.get(SaleOrderConstants.MANUAL_TOTAL_AMOUNT) : null);
                        }
                    }
                    return orderDetailDTO;
                }).collect(Collectors.toList());
                orderQueryResponse.setOrderDetailList(orderDetailDTOList);
            }

            DeliverOrderSDO deliverOrderSDO = new DeliverOrderSDO();
            if (order.getId() != null) {
                deliverOrderSDO.setOrderId(order.getId().toString());
            }
            deliverOrderSDO.setDetailAddress(order.getReceiveDetailAddress());
            deliverOrderSDO.setCustomerCode(order.getCustomerCode());
            deliverOrderSDO.setDeliveryPartCode(order.getDepartmentCode());
            deliverOrderSDO.setDeliveryPartName(order.getDepartmentName());
            deliverOrderSDO.setWarehouseCode(order.getWareHouseCode());
            deliverOrderSDO.setWarehouseName(order.getWareHouseName());
            deliverOrderSDO.setDeliveryTime(order.getCustomerExpectDate());
            deliverOrderSDO.setReceiveTime(order.getEndTime());
            deliverOrderSDO.setDeliveryStatus(order.getDeliveryStatus());
            deliverOrderSDO.setTransportModeCode(order.getTransportModeCode());
            deliverOrderSDO.setTransportModeName(order.getTransportModeName());
            deliverOrderSDO.setCreator(order.getCreatorName());
            deliverOrderSDO.setUpdater(order.getModifier());
            deliverOrderSDO.setContact(order.getContact());
            deliverOrderSDO.setContactPhone(order.getContactPhone());
            //子单
            List<DeliveryOrderDetailSDO> collect = orderQueryResponse.getOrderDetailList().stream().map(orderDetailDTO -> {
                DeliveryOrderDetailSDO detailSDO = new DeliveryOrderDetailSDO();
                detailSDO.setCustomerCode(order.getCustomerCode());
                detailSDO.setDeliveryTime(order.getCustomerExpectDate());
                detailSDO.setReceiveTime(order.getEndTime());
                detailSDO.setDeliveryStatus(order.getDeliveryStatus());
                detailSDO.setCreator(order.getCreatorName());
                detailSDO.setUpdater(order.getModifier());
                //          detailSDO.setDeliveryOrderId("1111");
                return detailSDO;
            }).collect(Collectors.toList());
            deliverOrderSDO.setDeliveryOrderDetailSDOS(collect);
            orderQueryResponse.setDeliverOrderSDO(deliverOrderSDO);
            return orderQueryResponse;
        }
        return new OrderQueryResponse();
    }

    @Override
    @RepositoryInvoker
    public OrderSDO querySingle(OrderQueryRequest request) {
        LoadOrderRequest loadOrderRequest = LoadOrderRequest.builder().build();
        loadOrderRequest.setId(request.getId());
        Order order = orderService.loadOrder(loadOrderRequest);


        OrderLineLoadListRequest orderLineLoadListRequest = new OrderLineLoadListRequest();
        orderLineLoadListRequest.setMainOrderId(request.getId());
        orderLineLoadListRequest.setStart(0);
        orderLineLoadListRequest.setLimit(999);
        OrderSDO orderSDO = new OrderSDO();
        LoadListResponse loadListResponse = orderLineService.loadList(orderLineLoadListRequest);
        if (loadListResponse != null) {
            List<OrderLine> result = loadListResponse.getResult();
            List<OrderLine> orderLineList = toList(result, OrderLine.class);
            orderSDO = OrderConvert.convertToOrderSDO(order, orderLineList);
        }

//            DeliverOrderSDO deliverOrderSDO = new DeliverOrderSDO();
//            deliverOrderSDO.setOrderId(order.getId().toString());
//            deliverOrderSDO.setDetailAddress(order.getReceiveDetailAddress());
//            deliverOrderSDO.setCustomerCode(order.getCustomerCode());
//            deliverOrderSDO.setDeliveryPartCode(order.getDepartmentCode());
//            deliverOrderSDO.setDeliveryPartName(order.getDepartmentName());
//            deliverOrderSDO.setWarehouseCode(order.getWareHouseCode());
//            deliverOrderSDO.setWarehouseName(order.getWareHouseName());
//            deliverOrderSDO.setDeliveryTime(order.getCustomerExpectDate());
//            deliverOrderSDO.setReceiveTime(order.getEndTime());
//            deliverOrderSDO.setDeliveryStatus(order.getDeliveryStatus());
//            deliverOrderSDO.setTransportModeCode(order.getTransportModeCode());
//            deliverOrderSDO.setTransportModeName(order.getTransportModeName());
//            deliverOrderSDO.setCreator(order.getCreatorName());
//            deliverOrderSDO.setUpdater(order.getModifier());
//            deliverOrderSDO.setContact(order.getContact());
//            deliverOrderSDO.setContactPhone(order.getContactPhone());
//            //子单
//            List<DeliveryOrderDetailSDO> collect = orderQueryResponse.getOrderDetailList().stream().map(orderDetailDTO -> {
//                DeliveryOrderDetailSDO detailSDO = new DeliveryOrderDetailSDO();
//                detailSDO.setCustomerCode(order.getCustomerCode());
//                detailSDO.setDeliveryTime(order.getCustomerExpectDate());
//                detailSDO.setReceiveTime(order.getEndTime());
//                detailSDO.setDeliveryStatus(order.getDeliveryStatus());
//                detailSDO.setCreator(order.getCreatorName());
//                detailSDO.setUpdater(order.getModifier());
//                return detailSDO;
//            }).collect(Collectors.toList());
//            deliverOrderSDO.setDeliveryOrderDetailSDOS(collect);
//            orderQueryResponse.setDeliverOrderSDO(deliverOrderSDO);
        return orderSDO;

    }

    private static <T> List<T> toList(List list, Class<T> clazz) {
        return JSONArray.parseArray(JSONObject.toJSONString(list), clazz);
    }


    private OrderQueryResponse OrderQueryResponseConverter(Order order) {
        OrderQueryResponse orderQueryResponse = new OrderQueryResponse();
        if (null != order.getId()) {
            orderQueryResponse.setId(String.valueOf(order.getId()));
        }
        orderQueryResponse.setFrontOrderId(order.getFrontOrderId());
        if (null != order.getStatus()) {
            orderQueryResponse.setOrderStatus(String.valueOf(order.getStatus()));
        }
        orderQueryResponse.setOrderBizId(order.getOrderBizId());
        orderQueryResponse.setAreaCode(order.getAreaCode());
        orderQueryResponse.setBisUnitCode(order.getBisUnitCode());
        orderQueryResponse.setSalesmanCode(order.getSalesmanId());
        orderQueryResponse.setUpdator(order.getModifierName());

        orderQueryResponse.setAddressCode(order.getReceiveAddressCode());
        orderQueryResponse.setReceiveAddressName(order.getReceiveDetailAddress());
        orderQueryResponse.setDeliveryAddr(order.getReceiveAddressCode());
        orderQueryResponse.setCustomerName(order.getCustomerName());
        orderQueryResponse.setCustomerCode(order.getCustomerCode());
        orderQueryResponse.setShippingWarehouse(order.getWareHouseCode());
        orderQueryResponse.setSalesOrganization(order.getOrganizationCode());
        orderQueryResponse.setBuzChannel(order.getChannelCode());
        orderQueryResponse.setSaleChannel(order.getSaleChannelCode());
        orderQueryResponse.setSaleDepartment(order.getDepartmentCode());
        orderQueryResponse.setOrderTag(order.getOrderTag());
        orderQueryResponse.setCustomerAccounts(order.getCustomerAccounts());
        orderQueryResponse.setCostCenter(order.getCostCenter());
        orderQueryResponse.setCashCustomerName(order.getCashCustomerName());
        orderQueryResponse.setCustomerRefNo(order.getCustomerReferenceNo());
        orderQueryResponse.setRemark(order.getRemark());
        orderQueryResponse.setGoodsGroup(order.getProductGroupCode());
        orderQueryResponse.setGoodsGroupName(order.getProductGroupName());
        orderQueryResponse.setOuterId(order.getOuterOrderId());
        if (null != order.getGmtModified()) {
            SimpleDateFormat spf = new SimpleDateFormat(STAN_DATETIME_PATTERN);
            orderQueryResponse.setUpdateTime(spf.format(order.getGmtModified()));
        }
        orderQueryResponse.setOrderReason(order.getCreateReason());
        orderQueryResponse.setFeatures(order.getFeatures());
        orderQueryResponse.setCreator(order.getCreatorName());
        if (null != order.getCustomerExpectDate()) {
            SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
            orderQueryResponse.setCustomerRefDate(spf.format(order.getCustomerExpectDate()));
        }
        orderQueryResponse.setContact(order.getContact());
        orderQueryResponse.setContactPhone(order.getContactPhone());
        orderQueryResponse.setDeliveryMethod(order.getTransportModeCode());
        orderQueryResponse.setOrderType(order.getOrderType());
        if (null != order.getGmtCreate()) {
            SimpleDateFormat spf = new SimpleDateFormat(STAN_DATETIME_PATTERN);
            orderQueryResponse.setOrderTime(spf.format(order.getGmtCreate()));
        }
        if (null != order.getOrderType()) {
            orderQueryResponse.setOrderTypeName(SaleOrderTag.of(order.getOrderType()).getDesc());
        }
        if (null != order.getOrganizationName()) {
            orderQueryResponse.setSalesOrganizationName(order.getOrganizationName());
        }
        orderQueryResponse.setBuzChannelName(order.getChannelName());
        orderQueryResponse.setSaleChannelName(order.getSaleChannelName());
        orderQueryResponse.setSaleDepartmentName(order.getDepartmentName());
        orderQueryResponse.setOrderReason(order.getCreateReason());
        orderQueryResponse.setDeliveryAddrName(order.getReceiveDetailAddress());
        orderQueryResponse.setShippingWarehouseName(order.getWareHouseName());
        orderQueryResponse.setDeliveryMethodName(order.getTransportModeName());
        orderQueryResponse.setSyncVersion(order.getSyncVersion());
        return orderQueryResponse;
    }

    private OrderDetailDTO OrderDetailDTOConverter(OrderLine orderLine) {
        OrderDetailDTO orderDetailDTO = new OrderDetailDTO();
        if (null != orderLine.getId()) {
            orderDetailDTO.setId(String.valueOf(orderLine.getId()));
        }
        orderDetailDTO.setOuterOrderLineId(orderLine.getOuterOrderLineId());
        orderDetailDTO.setGoodsCode(orderLine.getScItemOutCode());
        orderDetailDTO.setCategoryCode(orderLine.getCategoryCode());
        orderDetailDTO.setCategoryDesc(orderLine.getCategoryDesc());
        orderDetailDTO.setCategoryChildCode(orderLine.getCategoryChildCode());
        orderDetailDTO.setCategoryChildDesc(orderLine.getCategoryChildDesc());
        orderDetailDTO.setFirstCategoryCode(orderLine.getFirstCategoryCode());
        orderDetailDTO.setFirstCategoryDesc(orderLine.getFirstCategoryDesc());
        orderDetailDTO.setSecondCategoryCode(orderLine.getSecondCategoryCode());
        orderDetailDTO.setSecondCategoryDesc(orderLine.getSecondCategoryDesc());
        orderDetailDTO.setGoodsId(orderLine.getScItemId());
        orderDetailDTO.setGoodsName(orderLine.getScItemTitle());
        if (orderLine.getQuantity() != null) {
            orderDetailDTO.setQuantity(String.valueOf(orderLine.getQuantity()));
        }
        orderDetailDTO.setSaleUnit(orderLine.getSaleUnit());
        orderDetailDTO.setSaleUnitName(orderLine.getSaleUnitName());
        orderDetailDTO.setInventoryUnit(orderLine.getInventoryUnit());
        orderDetailDTO.setInventoryUnitCode(orderLine.getInventoryUnitCode());
        orderDetailDTO.setUnitConvert(orderLine.getUnitConvert());
        orderDetailDTO.setUnitPrice(orderLine.getUnitPrice());
        if (StringUtil.isNotEmpty(orderDetailDTO.getQuantity()) && StringUtil.isNotEmpty(orderDetailDTO.getUnitPrice())) {
            BigDecimal a = new BigDecimal(orderDetailDTO.getQuantity());
            BigDecimal b = new BigDecimal(orderDetailDTO.getUnitPrice());
            orderDetailDTO.setTotalAmount(String.valueOf(a.multiply(b)));
        }
        if (null != orderLine.getProductationTime()) {
            SimpleDateFormat sdf = new SimpleDateFormat(com.alibaba.citrus.ots.common.util.DateUtils.DATETIME_FORMAT);
            String format = sdf.format(orderLine.getProductationTime());
            orderDetailDTO.setProducteDate(format);
        }
        orderDetailDTO.setRemark(orderLine.getRemark());
        orderDetailDTO.setLineNum(orderLine.getSerialNumber());
        orderDetailDTO.setSaleQuantity(orderLine.getQuantity());
        orderDetailDTO.setFeatures(orderLine.getFeatures());
        if (!StringUtils.isEmpty(orderLine.getActivityPrice())) {
//            Double activityPrice = Double.valueOf(orderLine.getActivityPrice());
            orderDetailDTO.setActivityUnitPrice(orderLine.getActivityPrice());
        }
        if (StringUtils.isNotEmpty(orderLine.getActualPaidFee())) {
            orderDetailDTO.setActivityTotalAmount(orderLine.getActualPaidFee());
        }
        if (!StringUtils.isEmpty(orderLine.getCumulativeReceiptQuantity())) {
            orderDetailDTO.setCumulativeShipmentQuantity(Integer.parseInt(orderLine.getCumulativeReceiptQuantity()));
        }
        orderDetailDTO.setActivityId(orderLine.getActivityCode());
        orderDetailDTO.setActivityDesc(orderLine.getActivityName());
        orderDetailDTO.setRejectReason(orderLine.getRefuseReasonCode());
        orderDetailDTO.setOrderLineTag(orderLine.getOrderLineTag());
        orderDetailDTO.setFrontOrderLineId(orderLine.getFrontOrderLineId());
        orderDetailDTO.setDeliveryAmount(orderLine.getDeliveryAmount());
        if (null != orderLine.getStatus()) {
            orderDetailDTO.setOrderStatus(String.valueOf(orderLine.getStatus()));
            orderDetailDTO.setOrderStatusName(OrderStatus.of(orderLine.getStatus()).getDesc());
        }

        //设置活动行号
        String activityNumber = null;
        if (StringUtils.isNotBlank(orderLine.getFeatures())) {
            Map<String, String> features = JSONObject.parseObject(orderLine.getFeatures(), Map.class);
            if (MapUtils.isNotEmpty(features)) {
                if ("gift".equals(features.get("giftFlag"))) {
                    //设置赠品标识
                    orderDetailDTO.setIsGift(true);
                }

                List<ActivitySDO> activitySDOS = JSONObject.parseArray(features.get("activityDteails"), ActivitySDO.class);
                if (CollectionUtils.isNotEmpty(activitySDOS)) {
                    List<String> collect = activitySDOS.stream().map(ActivitySDO::getActivityTermid).collect(Collectors.toList());
                    activityNumber = collect.stream().collect(Collectors.joining("/"));
                }
            }
        }
        orderDetailDTO.setActivityLineNo(activityNumber);
        orderDetailDTO.setSyncVersion(orderLine.getSyncVersion());


        //todo 黔雷
//        GetScItemUnitInfoRequest getScItemUnitInfoRequest = new GetScItemUnitInfoRequest();
//        getScItemUnitInfoRequest.setScItemId(orderLine.getScItemId());
//        Map map = (Map) baseDataService.getScItemUnitInfo(getScItemUnitInfoRequest);
//        List<SelectCombox> selectComboxes = new ArrayList<>();
//        if (map.get("result") != null){
////                        List<SaleUnit> saleUnits = (List<SaleUnit>) map.get("result");
//            String js = JSON.toJSONString(map.get("result"));
//            List<SaleUnit> saleUnits = JSONArray.parseArray(js,SaleUnit.class);
//            if (CollectionUtils.isNotEmpty(saleUnits)){
//                selectComboxes = saleUnits.stream().map(saleUnit -> {
//                    SelectCombox selectCombox = new SelectCombox();
//                    selectCombox.setLabel(saleUnit.getUnitName()==null?saleUnit.getFeatures():saleUnit.getUnitName());
//                    selectCombox.setValue(saleUnit.getUnitCode());
//                    selectCombox.setExt(saleUnit.getRelationNum().toString());
//                    return selectCombox;
//                }).collect(Collectors.toList());
//            }
//            Map<String, SelectCombox> stringSelectComboxMap = selectComboxes.stream().collect(Collectors.toMap(SelectCombox::getValue, o->o,(k1, k2)->k2));
//            SelectCombox selectCombox1 = new SelectCombox();
//            selectCombox1.setValue(orderLine.getInventoryUnitCode());
//            selectCombox1.setLabel(orderLine.getInventoryUnit());
//
//            if (!stringSelectComboxMap.containsKey(orderLine.getInventoryUnitCode())) {
//                selectComboxes.add(selectCombox1);
//            }
//        }
        //orderDetailDTO.setSaleUnitList(selectComboxes);

        return orderDetailDTO;
    }

    private LoadOrderListRequest queryRequestConverter(OrderPageQueryRequest request) {
        LoadOrderListRequest loadOrderListRequest = new LoadOrderListRequest();
        if (!StringUtils.isEmpty(request.getId())) {
            loadOrderListRequest.setId(Long.parseLong(request.getId()));
        }
        loadOrderListRequest.setOrderTag(request.getOrderTag());
        loadOrderListRequest.setFrontOrderId(request.getFrontOrderId());
        loadOrderListRequest.setOuterOrderId(request.getOuterOrderId());
        loadOrderListRequest.setBizCode(request.getBizCode());
        loadOrderListRequest.setBusinessCode(request.getBusinessCode());
        loadOrderListRequest.setOrderType(request.getOrderType());
        loadOrderListRequest.setCustomerCode(request.getCustomerCode());
        loadOrderListRequest.setCustomerName(request.getCustomerName());
        loadOrderListRequest.setOrganizationCode(request.getOrganizationCode());
        loadOrderListRequest.setOrganizationName(request.getOrganizationName());
        if (!CollectionUtils.isEmpty(request.getDepartmentCodeList())) {
            loadOrderListRequest.setChannelList(request.getDepartmentCodeList());
        }
        loadOrderListRequest.setDepartmentName(request.getDepartmentName());
        if (!CollectionUtils.isEmpty(request.getProductGroupCodeList())) {
            loadOrderListRequest.setProductGroupCodeList(request.getProductGroupCodeList());
        }
        loadOrderListRequest.setProductGroupName(request.getProductGroupName());
        if (!CollectionUtils.isEmpty(request.getSaleChannelCodeList())) {
            loadOrderListRequest.setSaleChannelCodeList(request.getSaleChannelCodeList());
        }
        loadOrderListRequest.setSaleChannelName(request.getSaleChannelName());
        if (!CollectionUtils.isEmpty(request.getChannelCode())) {
            loadOrderListRequest.setChannelList(request.getChannelCode());
        }
        loadOrderListRequest.setChannelName(request.getChannelName());
        loadOrderListRequest.setReceiveAddressCode(request.getReceiveAddressCode());
        loadOrderListRequest.setReceiveDetailAddress(request.getReceiveDetailAddress());
        loadOrderListRequest.setStatus(request.getStatus());
        loadOrderListRequest.setOrderTotalFee(request.getOrderTotalFee());
        loadOrderListRequest.setActualPaidFee(request.getActualPaidFee());
        loadOrderListRequest.setShouldPayFee(request.getActualPaidFee());
        loadOrderListRequest.setPostFee(request.getPostFee());
        if (null != request.getPayStatus()) {
            loadOrderListRequest.setPayStatus(Integer.parseInt(request.getPayStatus()));
        }
        loadOrderListRequest.setPayTime(request.getPayTime());
        loadOrderListRequest.setDeliveryStatus(request.getDeliveryStatus());
        loadOrderListRequest.setEndTime(request.getEndTime());
        loadOrderListRequest.setTransportModeCode(request.getTransportModeCode());
        loadOrderListRequest.setTransportModeName(request.getTransportModeName());
        loadOrderListRequest.setWareHouseCode(request.getWareHouseCode());
        loadOrderListRequest.setWareHouseName(request.getWareHouseName());
        loadOrderListRequest.setCostCenter(request.getCostCenter());
        loadOrderListRequest.setCashCustomerName(request.getCashCustomerName());
        loadOrderListRequest.setSyncVersion(request.getSyncVersion());
        if (!CollectionUtils.isEmpty(request.getCreateReason())) {
            loadOrderListRequest.setCreateReasonList(request.getCreateReason());
        }
        loadOrderListRequest.setRemark(request.getRemark());
        loadOrderListRequest.setGmtCreate(request.getGmtCreate());
        loadOrderListRequest.setGmtModified(request.getGmtModified());
        loadOrderListRequest.setCreator(request.getCreator());
        loadOrderListRequest.setCreatorName(request.getCreatorName());
        loadOrderListRequest.setModifier(request.getModifier());
        loadOrderListRequest.setModifierName(request.getModifierName());
        loadOrderListRequest.setCustomerReferenceNo(request.getCustomerReferenceNo());
        loadOrderListRequest.setCustomerExpectDate(request.getCustomerExpectDate());
        loadOrderListRequest.setStart(request.getStart());
        loadOrderListRequest.setLimit(request.getLimit());
        loadOrderListRequest.setDir("gmtCreate");
        loadOrderListRequest.setAsc(false);
        return loadOrderListRequest;
    }

    @Override
    @RepositoryInvoker(errorCode = "OTS-05-001-10-16-001")
    public Result<List<OrderPageQueryResponse>> pageQueryES(PageQueryOrderEsListRequest request) {
        request.setDir("main_gmt_create");

        //单据创建日期
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(request.getOrderTime())) {
            request.setOrderStartTime(request.getOrderTime().get(0) == null ? null : DateUtils.string2Date(request.getOrderTime().get(0)));
            request.setOrderEndTime(request.getOrderTime().get(1) == null ? null : DateUtils.string2Date(request.getOrderTime().get(1)));
        }

        //单据修改日期
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(request.getUpdateTime())) {
            request.setUpdateStartTime(request.getUpdateTime().get(0) == null ? null : DateUtils.string2Date(request.getOrderTime().get(0)));
            request.setUpdateEndTime(request.getUpdateTime().get(1) == null ? null : DateUtils.string2Date(request.getOrderTime().get(1)));
        }

        Result<List<ObtcSaleOrderIndex>> listResult = obtcSaleOrderIndexService.pageQueryOrderList(request);
        if (CollectionUtils.isEmpty(listResult.getResult())) {
            return new Result<>();
        }
        List<ObtcSaleOrderIndex> result = listResult.getResult();


        List<OrderPageQueryResponse> orderPageQueryResponses = result.stream().map(obtcSaleOrderIndex -> {
            OrderPageQueryResponse orderPageQueryResponse = new OrderPageQueryResponse();
            if (null != obtcSaleOrderIndex.getMainId()) {
                orderPageQueryResponse.setId(String.valueOf(obtcSaleOrderIndex.getMainId()));
            }
            if (!StringUtils.isEmpty(obtcSaleOrderIndex.getMainOrderType())) {
//                String desc = Arrays.stream(SaleOrderTag.values()).filter(x -> obtcSaleOrderIndex.getMainOrderType().equals(x.getCode()))
//                        .map(SaleOrderTag::getDesc).findFirst().orElse(null);
                orderPageQueryResponse.setOrderType(SaleOrderTag.of(obtcSaleOrderIndex.getMainOrderType()).getDesc());
            }
            if (StringUtils.isNotBlank(obtcSaleOrderIndex.getMainFeatures())) {
                Map<String, String> features = JSONObject.parseObject(obtcSaleOrderIndex.getMainFeatures(), Map.class);
                orderPageQueryResponse.setMessageDesc(StringUtils.isNotBlank(features.get(SaleOrderConstants.EXT_MESSAGE)) ? features.get(SaleOrderConstants.EXT_MESSAGE) : null);
                orderPageQueryResponse.setFrontOrderBizId(StringUtils.isNotBlank(features.get(SaleOrderConstants.FRONT_ORDER_BIZ_ID)) ? features.get(SaleOrderConstants.FRONT_ORDER_BIZ_ID) : null);
                orderPageQueryResponse.setDeliveryOrderId(StringUtils.isNotBlank(features.get(SaleOrderConstants.DELIVERY_ORDER_ID)) ? features.get(SaleOrderConstants.DELIVERY_ORDER_ID) : null);
                orderPageQueryResponse.setCreditCheckStatus(features.get(SaleOrderConstants.CREDIT_CHECK_STATUS_NAME));
            }
            orderPageQueryResponse.setOrderBizId(obtcSaleOrderIndex.getMainOrderBizId());
            orderPageQueryResponse.setOuterId(obtcSaleOrderIndex.getMainOuterOrderId());
            orderPageQueryResponse.setCustomerName(obtcSaleOrderIndex.getMainCustomerName());
            orderPageQueryResponse.setSalesOrganization(obtcSaleOrderIndex.getMainOrganizationName());
            orderPageQueryResponse.setBuzChannel(obtcSaleOrderIndex.getMainChannelName());
            orderPageQueryResponse.setGoodsGroup(obtcSaleOrderIndex.getMainProductGroupName());
            orderPageQueryResponse.setSaleChannel(obtcSaleOrderIndex.getMainSaleChannelName());
            orderPageQueryResponse.setSaleDepartment(obtcSaleOrderIndex.getMainDepartmentName());
            orderPageQueryResponse.setCreator(obtcSaleOrderIndex.getMainCreatorName());
            orderPageQueryResponse.setRemark(obtcSaleOrderIndex.getMainRemark());
            orderPageQueryResponse.setReceiveAddressCode(obtcSaleOrderIndex.getMainReceiveAddressCode());
            orderPageQueryResponse.setReceiveDetailAddressName(obtcSaleOrderIndex.getMainReceiveDetailAddress());
            orderPageQueryResponse.setWareHouseCode(obtcSaleOrderIndex.getMainWareHouseCode());
            orderPageQueryResponse.setFrontOrderId(obtcSaleOrderIndex.getMainFrontOrderId());
            orderPageQueryResponse.setCustomerRefNo(obtcSaleOrderIndex.getMainCustomerReferenceNo());

            if (obtcSaleOrderIndex.getMainStatus() != null) {
                orderPageQueryResponse.setStatusCode(String.valueOf(obtcSaleOrderIndex.getMainStatus()));
                String desc = OrderStatus.of(Integer.parseInt(String.valueOf(obtcSaleOrderIndex.getMainStatus()))).getDesc();
                orderPageQueryResponse.setStatus(desc);
            }
            if (null != obtcSaleOrderIndex.getMainGmtCreate()) {
                SimpleDateFormat spf = new SimpleDateFormat(STAN_DATETIME_PATTERN);
                String format = spf.format(obtcSaleOrderIndex.getMainGmtCreate());
                orderPageQueryResponse.setOrderTime(format);
            }

            return orderPageQueryResponse;
        }).collect(Collectors.toList());
        return Result.listSuccess(orderPageQueryResponses, listResult.getTotal());

    }

}
